//
//  MessageDetailController.m
//  QQplayground
//
//  Created by zhangxy on 2018/8/15.
//  Copyright © 2018年 zhang. All rights reserved.
//

#import "MessageDetailController.h"
#import "MessageEntity.h"
#import "MyButton.h"

#import "ZZMessageItemCell.h"
#define cellIdentifier @"ZZMessageItemCell"

#import "UserInfoController.h"
#import "ZZContentDetailController.h"
#import "TalkDetailController.h"

#import "ZZLeaveMessageController.h"

#import "ZZKeyboardView.h"

@interface MessageDetailController ()<ZZMessageItemCellDelegate,UIGestureRecognizerDelegate>{
    NSString *image_id;
    
    MessageDetailEntity *checkModel;
}
@property(nonatomic,assign) int page;

@property(nonatomic,strong)  NSMutableArray *listArray;
@property(nonatomic,strong)  UITableView *listTable;


@property(nonatomic,strong)  ZZKeyboardView   *keyboardView;

@end

@implementation MessageDetailController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    // Do any additional setup after loading the view.
    self.navigationItem.title = _model.title;
    [self setNavigationBar];
    
    self.navigationController.navigationBarHidden = NO;
    
    
    [self createTableView];
    
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [self loadBegin];
    
    _keyboardView = [[ZZKeyboardView alloc] initWithDelegate:self changeView:_listTable show:NO style:ZZKeyboardControlsAddPhoto];
//    _keyboardView.chatpterModel = _model;
    __weak MessageDetailController *saveSelf = self;
    [_keyboardView setResultBlock:^(int code,NSString *text,id replayModel){
        if(code == 0){
            
            NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
            [dict setObject:convertToString([UserUtil getUser].user_id) forKey:@"session_uid"];
            [dict setObject:convertToString(text) forKey:@"message"];
            [dict setObject:convertToString(self->image_id) forKey:@"img_id"];
            
            NSString *type = checkModel.mapping_info.type;
            NSString *messageId = checkModel.mapping_info.mapping_id;
            MessageMappingEntity *tempModel = checkModel.mapping_root_info;
            if(tempModel!=nil){
                [dict setObject:convertToString(tempModel.mapping_id) forKey:@"quote_id"];
                [dict setObject:convertToString(checkModel.user_info.user_id) forKey:@"quote_uid"];
                type = tempModel.type;
                messageId = tempModel.mapping_id;
            }else{
                MessageMappingEntity *tempModel1 = checkModel.mapping_parent_info;
                if(tempModel1!=nil){
                    [dict setObject:convertToString(tempModel1.mapping_id) forKey:@"quote_id"];
                    [dict setObject:convertToString(checkModel.user_info.user_id) forKey:@"quote_uid"];
                    type = tempModel1.type;
                    messageId = tempModel1.mapping_id;
                }else{
                [dict setObject:@"0" forKey:@"quote_id"];
                [dict setObject:@"0" forKey:@"quote_uid"];
                }
            }
            [dict setObject:convertToString(messageId) forKey:@"id"];
            
            if([@"thread" isEqual:type]){
                NSMutableDictionary *dict1 = [[NSMutableDictionary alloc] init];
                [dict1 setObject:convertToString(messageId) forKey:@"thread_id"];
                [dict1 setObject:convertToString([UserUtil getUser].user_id) forKey:@"session_uid"];
//                [dict setObject:convertToString(saveSelf.model.cat_id) forKey:@"cat_id"];
                
                [dict1 setObject:convertToString(text) forKey:@"message"];
                [dict1 setObject:@"reply" forKey:@"action_type"];
                [dict1 setObject:convertToString(image_id) forKey:@"img_id"];
                
                NSString *api = API_publishPost;
                if(![dict[@"quote_id"] isEqual:@"0"]){
                    [dict setObject:convertToString(dict[@"quote_id"]) forKey:@"post_id"];
                    
                    api = API_publishReplyPost;
                }
                
                [NetworkUtil POST:api parameters:dict success:^(id responseObject, NSDictionary *dict) {
//                    ZZTopicCommentEntity *addModel = [[ZZTopicCommentEntity alloc] initWithDictionary:dict[@"data"]];
//                    if(replayModel!=nil){
//                        ZZTopicCommentEntity *com = replayModel;
//                        [com.thread_list insertObject:addModel atIndex:0];
//                    }else{
//                        [saveSelf.listArray insertObject:addModel atIndex:0];
//                    }
//                    [saveSelf.listTable reloadData];
                    [self pageClick:nil];
                } failure:^(NSError *error, NSString *message) {
                    [self pageClick:nil];
                }];
            }else{
                [NetworkUtil POST:API_publishComment(type) parameters:dict success:^(id responseObject, NSDictionary *dict) {
    //                ZZTopicCommentEntity *addModel = [[ZZTopicCommentEntity alloc] initWithDictionary:dict[@"data"]];
    //                if(replayModel!=nil){
    //                    ZZTopicCommentEntity *com = replayModel;
    //                    [com.thread_list insertObject:addModel atIndex:0];
    //                }else{
    //                    [saveSelf.listArray insertObject:addModel atIndex:0];
    //                }
    //                [saveSelf.listTable reloadData];
                    [self pageClick:nil];
                } failure:^(NSError *error, NSString *message) {
    //                [PopUtil showMessage:message];
                    [self pageClick:nil];
                }];
            }
        }
    }];
    
    _keyboardView.hidden = YES;
    UITapGestureRecognizer *oneTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(pageClick:)];
    oneTap.delegate = self;
    oneTap.numberOfTouchesRequired = 1;
    [self.view addGestureRecognizer:oneTap];
    
    
}


-(void)pageClick:(UITapGestureRecognizer *) tap{
    [_keyboardView hideKeyboard];
    
    _keyboardView.hidden = YES;
}

- (void)imagePickerDidFinishedWithInfo:(NSDictionary *)info image:(UIImage *) thumIamge file:(NSURL *) url type:(ImagePickerDelegateType) type{
    if(thumIamge){
        NSData *data = UIImageJPEGRepresentation(thumIamge,0.3);
        NSString *type = checkModel.mapping_info.type;
        NSString *messageId = checkModel.mapping_info.mapping_id;
        MessageMappingEntity *tempModel = checkModel.mapping_root_info;
        if(tempModel!=nil){
            type = tempModel.type;
        }else{
            MessageMappingEntity *tempModel1 = checkModel.mapping_parent_info;
            if(tempModel1!=nil){
                type = tempModel1.type;
            }
        }
        NSString *api = API_publishCommentuploadthread(type);
        if([@"thread" isEqual:type]){
            api = API_ForumUpload;
        }
        [ImageUploadUtil uploadImage:data api:api  param:@{@"session_uid":[UserUtil getUser].user_id} callback:^(NSString *imageurl, NSDictionary *videoDict, NSString *message) {
            NSLog(@"%@",videoDict);
            
            if(videoDict){
                self->image_id = videoDict[@"image_id"];
                if(_keyboardView){
                    [_keyboardView setUploadResutl:videoDict image:thumIamge];
                }
            }else{
                [PopUtil showMessage:message];
            }
            
        }];
    }
}


#pragma mark - UIGestureRecognizerDelegate
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
    // 输出点击的view的类名
    NSLog(@"%@", NSStringFromClass([touch.view class]));
    
    // 若为UITableViewCellContentView（即点击了tableViewCell），则不截获Touch事件
    if ([NSStringFromClass([touch.view class]) isEqualToString:@"UITableViewCellContentView"]) {
        [_keyboardView hideKeyboard];
        return NO;
    }
    return  YES;
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    self.navigationController.navigationBarHidden = NO;
}


-(void)createTableView{
    _listArray = [[NSMutableArray alloc] init];
    
    _listTable=[self.view createTableView:self cell:cellIdentifier];
    [_listTable setFrame:self.view.bounds];
    _listTable.layer.cornerRadius = 10.0f;
    _listTable.layer.masksToBounds = YES;
    [_listTable setBackgroundColor:UIColorFromRGB(TextWhiteColor)];
    
    if (iOS7) {
        _listTable.backgroundView = nil;
    }
    UIView *footer =[ [UIView alloc]init];
    footer.backgroundColor = [UIColor clearColor];
    [_listTable setTableFooterView:footer];
    
    [_listTable setSeparatorColor:LINE_COLOR];
    [_listTable setSeparatorStyle:UITableViewCellSeparatorStyleSingleLine];
    
    
    [self setTableSeparatorInset];
    
    MJRefreshStateHeader *header = [MJRefreshStateHeader headerWithRefreshingBlock:^{
        [self loadBegin];
    }];
    
    MJRefreshBackNormalFooter *mjfooter = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        [self loadMoreData];
    }];
    [mjfooter setTitle:Uncontent_floor forState:MJRefreshStateNoMoreData];
    
    _listTable.header = header;
    _listTable.footer = mjfooter;
}




-(void)loadBegin{
    _page = 1;
    
    [self.listTable.footer endRefreshing];  //修改footer状态
    [self loadMoreData];
}

/**
 加载更多
 */
-(void)loadMoreData{
    NSDictionary *params = @{@"session_uid":convertToString([UserUtil getUser].user_id),
                             @"feed_type":convertToString(self.model.type),
                             @"page":convertIntToString(_page)
                             };
    [NetworkUtil POST:API_GetMessageListWithType parameters:params success:^(id responseObject, NSDictionary *dict) {
        NSArray *arr = dict[@"data"][@"list"];
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        if([self.listTable.header isRefreshing]){
            [self.listTable.header endRefreshing];
        }
        if([self.listTable.footer isRefreshing]){
            if ([dict[@"data"][@"page"] intValue] <= self.page) {
                [self.listTable.footer endRefreshingWithNoMoreData];
            }else{
                [self.listTable.footer endRefreshing];
            }
        }
        if(self.page == 1){
            [self.listArray removeAllObjects];
        }
        for (NSDictionary *item in arr) {
            [self->_listArray addObject:[[MessageDetailEntity alloc] initWithDictionary:item]];
        }
        
        [self.listTable reloadData];
        
        self.page = [dict[@"data"][@"page"] intValue] + 1;
        
//        if(arr.count == 0){
//            [_listTable setTableFooterView:[self createTableFooter]];
//        }
        
        
    } failure:^(NSError *error, NSString *message) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        if([self.listTable.header isRefreshing]){
            [self.listTable.header endRefreshing];
        }
        if([self.listTable.footer isRefreshing]){
            [self.listTable.footer endRefreshing];
        }
//        [PopUtil showMessage:message];
    }];
}


-(void)onCellOpenClick:(id) sender{
    [self openPushVC:sender];
}

-(void)onItemReply:(MessageDetailEntity *)senderObj{
    checkModel = senderObj;
    
    _keyboardView.hidden = NO;
    [_keyboardView setReplyModel:senderObj];
}


#pragma mark UITableView delegate Start
// 返回section数
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

// 返回section高度
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 1;
}

// 返回section 的View
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectZero];
    
    
    return headerView;
}

// 返回section下得行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _listArray.count;
}

// cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    ZZMessageItemCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil) {
        cell = [[ZZMessageItemCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier] ;
    }
    cell.delegate = self;
    [cell dataToView:_listArray[indexPath.row]];
    
    return cell;
}



// 是否显示删除功能
-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{
    return NO;
}

// 删除清理数据
-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    editingStyle = UITableViewCellEditingStyleDelete;
}


// table 行的高度
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //    return 70.0f;
    UITableViewCell *cell = [self tableView:tableView cellForRowAtIndexPath:indexPath];
    return cell.frame.size.height;
}

// table 行的点击事件
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    MessageDetailEntity *model=[_listArray objectAtIndex:indexPath.row];
    
    // 赞
    if([@"like" isEqual:model.type]){
        // 赞了人
        if([@"user" isEqual:convertToString(model.mapping_info.type)]){
            UserInfoController *detail = [[UserInfoController alloc] init];
            detail.user_id = model.user_info.user_id;
            [self openPushVC:detail];
        }else{
            ZZContentDetailController *detail = [[ZZContentDetailController alloc] init];
            ZZHomeTopicEntity *en = [ZZHomeTopicEntity new];
            en.t_id = [model.mapping_info.mapping_id integerValue];
            en.nav_type = convertToString(model.mapping_info.type);
            en.nav_name = [en getElementTitle:en.nav_type];
            detail.entity = en;
            [self openPushVC:detail];
        }
    }else{
        // 跳转到内容回复
        if([@"comment_reply" isEqual:model.mapping_info.type]){
            ZZContentDetailController *detail = [[ZZContentDetailController alloc] init];
            ZZHomeTopicEntity *en = [ZZHomeTopicEntity new];
            en.t_id = [model.mapping_root_info.mapping_id integerValue];
            en.nav_type = convertToString(model.mapping_root_info.type);
            en.nav_name = [en getElementTitle:en.nav_type];
            detail.entity = en;
            
            
            ZZTopicCommentEntity *cen = [ZZTopicCommentEntity new];
            cen.user_info = model.user_info;
            cen.comment_id = model.mapping_info.mapping_id;
            detail.replayModel = cen;
            [self openPushVC:detail];
        }else if([@"thread" isEqual:model.mapping_info.type]){
            TalkDetailController *detail = [[TalkDetailController alloc] init];
            ForumEntity *en = [ForumEntity new];
            en.thread_id = model.mapping_info.mapping_id;
            detail.model = en;
            [self openPushVC:detail];
        }else if([@"thread_comment" isEqual:model.mapping_info.type]){
            TalkDetailController *detail = [[TalkDetailController alloc] init];
            ForumEntity *en = [ForumEntity new];
            en.thread_id = model.mapping_parent_info.mapping_id;
            detail.model = en;
            
            ZZTopicCommentEntity *cen = [ZZTopicCommentEntity new];
            cen.user_info = model.user_info;
            cen.comment_id = model.mapping_info.mapping_id;
            detail.replyModel = cen;
            
            [self openPushVC:detail];
        }else if([@"thread_comment_reply" isEqual:model.mapping_info.type]){
            TalkDetailController *detail = [[TalkDetailController alloc] init];
            ForumEntity *en = [ForumEntity new];
            en.thread_id = model.mapping_root_info.mapping_id;
            detail.model = en;
            
            ZZTopicCommentEntity *cen = [ZZTopicCommentEntity new];
            cen.user_info = model.user_info;
            cen.comment_id = model.mapping_info.mapping_id;
            detail.replyModel = cen;
            
            [self openPushVC:detail];
        }else if([@"comment" isEqual:model.mapping_info.type]){
            ZZContentDetailController *detail = [[ZZContentDetailController alloc] init];
            ZZHomeTopicEntity *en = [ZZHomeTopicEntity new];
            en.t_id = [model.mapping_parent_info.mapping_id integerValue];
            en.nav_type = convertToString(model.mapping_parent_info.type);
            en.nav_name = [en getElementTitle:en.nav_type];
            detail.entity = en;
            
            
            ZZTopicCommentEntity *cen = [ZZTopicCommentEntity new];
            cen.user_info = model.user_info;
            cen.comment_id = model.mapping_info.mapping_id;
            detail.replayModel = cen;
            [self openPushVC:detail];
        }else if([@"wall" isEqual:model.mapping_info.type]){
            ZZLeaveMessageController *detail = [[ZZLeaveMessageController alloc] init];
            detail.user_id = model.user_info.user_id;
           
            [self openPushVC:detail];
        }else if([@"wall_reply" isEqual:model.mapping_info.type]){
            ZZLeaveMessageController *detail = [[ZZLeaveMessageController alloc] init];
            detail.user_id = model.user_info.user_id;
            
//             model.mapping_info.mapping_id
//            model.mapping_parent_info.mapping_id
            [self openPushVC:detail];
        }else{
            // 赞了人
            if([@"user" isEqual:convertToString(model.mapping_info.type)]){
                UserInfoController *detail = [[UserInfoController alloc] init];
                detail.user_id = model.user_info.user_id;
                [self openPushVC:detail];
            }else{
                ZZContentDetailController *detail = [[ZZContentDetailController alloc] init];
                ZZHomeTopicEntity *en = [ZZHomeTopicEntity new];
                en.t_id = [model.mapping_info.mapping_id integerValue];
                en.nav_type = convertToString(model.mapping_info.type);
                en.nav_name = [en getElementTitle:en.nav_type];
                detail.entity = en;
                [self openPushVC:detail];
            }
        }
    }
    
    
}

//设置分割线间距
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
    if((indexPath.row+1) < _listArray.count){
        UIEdgeInsets inset = UIEdgeInsetsMake(0, 10, 0, 0);
        if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
            [cell setSeparatorInset:inset];
        }
        
        if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
            [cell setLayoutMargins:inset];
        }
    }
}

-(void)viewDidLayoutSubviews{
    [self setTableSeparatorInset];
}
#pragma mark UITableView delegate end

/**
 *  设置UITableView分割线空隙
 */
-(void)setTableSeparatorInset{
    UIEdgeInsets inset = UIEdgeInsetsMake(0, 10, 0, 0);
    if ([_listTable respondsToSelector:@selector(setSeparatorInset:)]) {
        [_listTable setSeparatorInset:inset];
    }
    
    if ([_listTable respondsToSelector:@selector(setLayoutMargins:)]) {
        [_listTable setLayoutMargins:inset];
    }
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
